-- UISkyActivityBonus
-- Create by chendh
-- 天空活动奖励说明界面

-- UISkyActivityBonus继承自Layer
UISkyActivityBonus = class("UISkyActivityBonus", function()
    return cc.Layer:create();
end);

local PER_LINE_WORD_COUNT   = 21;
local LINE_HEIGHT           = 34;
local BONUS_GRID_HEIGHT     = 110;

function UISkyActivityBonus.create(activityId)
    return UISkyActivityBonus.new(activityId);
end

-- 内部函数声明

-- 构造函数
function UISkyActivityBonus:ctor(activityId)
    -- 初始化
    self:setName("UISkyActivityBonus");
    local node = cc.CSLoader:createNode("layout/sky_city/SkyActivityBonus.csb");
    self:addChild(node);
    self.node = node;

    self.activityId = activityId;

    local CT = node:getChildByName("CT");
    local scrollview = CT:getChildByName("scroll_view");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);

    -- 垂直滑动，需要显示上下蒙版
    local mask1 = findChildByName(self.node, "CT/mask1");
    mask1:setVisible(true);
    local mask2 = findChildByName(self.node, "CT/mask2");
    mask2:setVisible(true);

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化奖励说明数据
    self:initData();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UISkyActivityBonus:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化奖励说明数据
function UISkyActivityBonus:initData()
    local hasBonus      = false;
    local data          = {};
    local userBonus     = {};
    local bonusList     = SkyActivityM.getActivityBonusList(self.activityId);
    local activityData  = SkyActivityM.getActivityData(self.activityId) or {};
    local curScore      = activityData["score"] or 0;

    -- 计算出当前积分是否可以获得奖励
    for _, info in ipairs(bonusList) do
        if curScore >= info["score"] then
            userBonus = info;
            hasBonus  = true;
            break;
        end
    end

    -- 插入当前积分情况
    if hasBonus then
        -- 玩家当前可获得积分奖励
        table.insert(data, getLocStr("sky_activity_bonus_info1"));
        table.insert(data, string.format(getLocStr("sky_activity_bonus_info2"), curScore, userBonus["name"]));
        table.insert(data, getLocStr("sky_activity_bonus_info3"));

        table.insert(data, userBonus);
    else
        -- 玩家当前无法获得积分奖励
        table.insert(data, getLocStr("sky_activity_bonus_info1"));
        table.insert(data, string.format(getLocStr("sky_activity_bonus_info4"), curScore));
    end

    -- 插入活动说明
    for i=5, 12 do
        table.insert(data, getLocStr("sky_activity_bonus_info" .. i));
    end

    self.data = data;
    self.bonusList = bonusList;
end

-- 创建格子
function UISkyActivityBonus:creaeteGrids(info)
    local grid;
    local height;
    if type(info) == "string" then
        grid, height = self:creaeteStringGrids(info);
    else
        grid, height = self:creaeteBonusGrids(info);
    end

    return grid, height;
end

-- 创建文本格子
function UISkyActivityBonus:creaeteStringGrids(info)
    local textNode = ccui.Text:create();
    textNode:getVirtualRenderer():setHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT);
    textNode:getVirtualRenderer():setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER);
    textNode:getVirtualRenderer():setLineHeight(LINE_HEIGHT);
    textNode:setFontName(getLocFontName());
    textNode:setAnchorPoint(0, 1);

    -- 不同语言版本需要根据字号的统一缩放增加下每行的字数
    local locFix = getLocFontSizeMulti();

    TextStyleM.setTextStyle(textNode, TextStyleM.TEXT_SIZE_SMALL2,
        TextStyleM.TEXT_COLOR_DARK_BROWN, false, -1, nil, nil, PER_LINE_WORD_COUNT / locFix);

    textNode = applyString(textNode, info, nil, nil, LINE_HEIGHT);

    local height = textNode:getContentSize().height;
    local lineNum = textNode:getVirtualRenderer():getStringNumLines();

    for i=1, lineNum do
        local image = ccui.ImageView:create();
        image:loadTexture(getTalentIconPath("line"));
        image:setPosition(cc.p(0, height - LINE_HEIGHT * i));
        image:setScaleX(0.8);
        image:setAnchorPoint(0, 0);
        textNode:addChild(image);
    end
    return textNode, height;
end

-- 创建奖励格子
function UISkyActivityBonus:creaeteBonusGrids(info)
    local item          = cc.CSLoader:createNode("layout/sky_city/SkyActivityBonusItem.csb");
    local node          = replaceNodeWithWidget(item);
    local rankLabel     = node:getChildByName("rank");
    local scoreLabel    = node:getChildByName("score");
    local rankBg        = node:getChildByName("rank_bg");

    rankBg:loadTexture(getItemIconPath(10002));

    TextStyleM.setTextStyle(rankLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -3);
    rankLabel:setString(info["name"]);
    TextStyleM.setTextStyle(scoreLabel, TextStyleM.TEXT_SIZE_TINY, TextStyleM.TEXT_COLOR_CREAM, true, -3);
    scoreLabel:setString(info["score"]);

    local bonusNum = #info["bonus"];
    for index, bonus in ipairs(info["bonus"]) do
        local bonusNode = node:getChildByName("bonus" .. 4 - bonusNum + index);
        bonusNode = replaceNodeWithWidget(bonusNode);
        bonusNode:setVisible(true);

        local bgImg = bonusNode:getChildByName("bg");
        local icon = bonusNode:getChildByName("icon");
        local numLabel = bonusNode:getChildByName("num");

        local iconPath;
        local classId   = bonus[2];
        local num       = bonus[3];
        if bonus[1] == 1 then
            -- 道具类奖励
            iconPath = getItemIconPath(ItemM.query(classId, "icon"));
        elseif bonus[1] == 2 then
            -- 属性类奖励
            iconPath = getLargeAttribIconPath(Fields.query(classId, "icon"));
        elseif bonus[1] == 6 then
            -- 秘宝类奖励
            iconPath = getAirShipSkillIconPath(SkyShipSkillM.query(classId, "icon"));
        end

        icon:loadTexture(iconPath);

        TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_CREAM, true, -3);
        numLabel:setString(changeNumType(num));
        --bgImg:setTouchEnabled(true);
        bgImg:addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                showBonusDesc(bonus);
             end
        end);
    end

    return node, BONUS_GRID_HEIGHT;
end

-- 显示商店
function UISkyActivityBonus:redraw()
    -- 显示标题
    local titleLabel = findChildByName(self.CT, "title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("sky_activity_bonus_title"));

    -- 绘制倒计时
    self:redrawTime();

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    -- 绘制当前积分和活动说明
    local totalHeight = 0;
    for _, info in ipairs(self.data) do
        local grid, gridHeight = self:creaeteGrids(info);

        self.scrollView:addChild(grid);
        table.insert(self.scrollView.rows, grid);

        grid.info = info;
        grid.height = totalHeight;

        totalHeight = totalHeight + gridHeight;

        if type(info) ~= "string" then
            -- 如果不是文本信息，那么需要显示下奖励框的背景
            local bgImg = grid:getChildByName("bg");
            bgImg:setVisible(true);
        end
    end

    -- 高度增加10，给奖励列表上下留出一定空间
    totalHeight = totalHeight + 20;

    -- 在奖励列表的时候希望排列紧凑一点，所以这里主动把高度减去了10
    local curBonusHeight = BONUS_GRID_HEIGHT - 10;
    -- 绘制积分奖励列表背景
    local bonusBg = ccui.ImageView:create();
    bonusBg:loadTexture(getTitleBgIconPath("point_blue"));
    -- 设置为九宫格模式
    bonusBg:setScale9Enabled(true);
    bonusBg:setCapInsets(cc.rect(6, 6, 6, 6));
    bonusBg:setContentSize(cc.size(460, #self.bonusList * curBonusHeight));
    bonusBg:setPosition(250, #self.bonusList * curBonusHeight / 2 + 5);
    self.scrollView:addChild(bonusBg);

    -- 绘制积分奖励列表
    for _, info in ipairs(self.bonusList) do
        local grid = self:creaeteBonusGrids(info);

        grid.info = info;
        grid.height = totalHeight - 10;
        totalHeight = totalHeight + curBonusHeight;

        self.scrollView:addChild(grid);
        table.insert(self.scrollView.rows, grid);
    end

    -- 整理所有格子的坐标
    self.scrollView:setInnerContainerSize(cc.size(450, totalHeight));

    for index, node in ipairs(self.scrollView.rows) do
        node.index = index;
        node:setPositionX(20);
        node:setPositionY(totalHeight - node.height - 10);
    end

    self.scrollView:jumpToPercentBothDirection(cc.p(0, 100));
end

-- 绘制时间
function UISkyActivityBonus:redrawTime()
    if self.isTick then
        return;
    end
    local function tick()
        -- 提示信息
        local leftTime = ActivityM.getRemainTime(self.activityId);
        local txt1Label = findChildByName(self.CT, "subhead");

        TextStyleM.setSubheadStyle(txt1Label);

        if leftTime > 0 then
            txt1Label:setString(string.format(getLocStr("sky_activity_bonus_time"), remainingTimeDesc(leftTime)));

            performWithDelay(self, tick, 1);
        else
            txt1Label:setString(getLocStr("closed"));
        end
    end
    self.isTick = true;
    tick();
end

-- 注册事件处理回调函数
function UISkyActivityBonus:registerEventCallback()
    -- 关注活动关闭事件
    EventMgr.register("UISkyActivityBonus", event.ACTIVITY_CLOSE, function(args)
        -- 如果是当前活动关闭了，那么退出奖励说明界面
        if self.activityId == args["id"] then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyActivityBonus");
        end
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UISkyActivityBonus", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UISkyActivityBonus" then
            -- TopMenu显示天空活动的数据和袭击次数
            local uiTopMenu = UIMgr:getCurrentScene().topMenu;
            uiTopMenu:setSkyActivityId(self.activityId);
            uiTopMenu:show(TOPMENU_FRAME_ACTIVITY_DATA, TOPMENU_FRAME_ACTIVITY_TIMES, TOPMENU_FRAME_HEAD_AIRSHIP);

            -- 显示界面
            self:setVisible(true);
        elseif para["lose"] == "UISkyActivityBonus" then
            if para["get"] == "UIActivityExchange" or
                para["get"] == "UIActivityRankingList" then
                -- 隐藏界面
                self:setVisible(false);
            end
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UISkyActivityBonus");
        end
    end);
end

-- 注册点击事件
function UISkyActivityBonus:registerTouchEvent()
    -- 注册兑换按钮点击事件
    local btnExchange = findChildByName(self.node, "BT/btn_exchange");
    local function onExchangeClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            require "game/ui/form/activity/UIActivityExchange"
            local uiForm = UIActivityExchange.create(self.activityId);
            UIMgr.getCurrentScene():addForm(uiForm);
        end
    end
    btnExchange:addTouchEventListener(onExchangeClick);
    TextStyleM.setTextStyle(btnExchange, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnExchange:setTitleText(getLocStr("sky_activity_exchange_title"));

    -- 注册排行榜按钮点击事件
    local btnTop = findChildByName(self.node, "BT/btn_top");
    local function onTopClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 直接重新获取下数据
            Operation.cmd_get_activity_top_list(self.activityId);

            require "game/ui/form/sky_city/UISkyActivityRankingList"
            local uiForm = UISkyActivityRankingList.create(self.activityId);
            UIMgr.getCurrentScene():addForm(uiForm);
        end
    end
    btnTop:addTouchEventListener(onTopClick);
    TextStyleM.setTextStyle(btnTop, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnTop:setTitleText(getLocStr("leaderboard"));

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyActivityBonus");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end
